import Vue from 'vue'
import VueRouter from 'vue-router'

import store from '@/store'
import { Toast } from 'vant'
// import login from '@/views/login'
// import layout from '@/views/layout'
// import home from '@/views/home'
// import ask from '@/views/ask'
// import mine from '@/views/mine'
// import video from '@/views/video'
// import UserEdit from '@/views/mine/UserEdit'
// import article from '@/views/article'
// import search from '@/views/search'
// import result from '@/views/search/MyResult'
// import chat from '@/views/mine/MyChat'

const login = () => import('@/views/login')
const layout = () => import('@/views/layout')
const home = () => import('@/views/home')
const ask = () => import('@/views/ask')
const mine = () => import('@/views/mine')
const video = () => import('@/views/video')
const UserEdit = () => import('@/views/mine/UserEdit')
const article = () => import('@/views/article')
const search = () => import('@/views/search')
const result = () => import('@/views/search/MyResult')
const chat = () => import('@/views/mine/MyChat')
// 解决3.1版本后在控制台出现的警告
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)
const routes = [
  { path: '/', redirect: '/layout/home' },
  { name: 'login', path: '/login', component: login },
  { name: 'UserEdit', path: '/mine/edit', component: UserEdit },
  { name: 'article', path: '/article/:id', component: article },
  { name: 'search', path: '/search', component: search },
  { name: 'result', path: '/search/result', component: result },
  { name: 'chat', path: '/chat', component: chat },
  {
    name: 'layout',
    path: '/layout',
    component: layout,
    children: [
      { name: 'home', path: 'home', component: home },
      { name: 'ask', path: 'ask', component: ask },
      { name: 'video', path: 'video', component: video },
      {
        name: 'mine',
        path: 'mine',
        component: mine,
        meta: {
          needLogin: true
        }
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// to： 去哪 -- 得到的是路由信息对象
// from： 从哪来 -- 得到的是路由对象信息
// next： 放行的函数，调用它就代表放行
// $router.push能怎么用，next就能怎么用
router.beforeEach((to, from, next) => {
  if (to.meta.needLogin) {
    // 满足这个if代表要去的是需要登录的页面
    // 判断是否登录--有没有token
    if (store.state.user.tokenObj.token) {
      // 有token
      next()
    } else {
      // 没有登录，放行到登录页
      Toast('请先登录')
      // 打回登录页之前应该把要去的路径记录起来
      // 所以可以直接把要去的路径当做参数传递给登录页
      next({
        name: 'login',
        query: {
          back: to.path
        }
      })
    }
  } else {
    // 代表不需要登录的页面，直接放行
    next()
  }
})

export default router
